package com.test.latitudex.utilities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.message.BasicHeader;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.test.latitudex.utilities.NetworkManager.HttpRequestListener;

public class RegistrationManager implements HttpRequestListener {

	private static final String LOG_TAG = "RegistrationManager";
	public static final String PREFS_NAME = "MyPrefs";
	private static NetworkManager nm;
	private static final String defUser = "useradmin";
	private static final String defPass = "abcd1234";
	public static final String IS_LOGGED_IN = "isLoggedIn";
	public static final String FROM_LOGOUT = "fromLogout";
	private static String id = null;
	private static Context ctx;
	private static String email = null;
	private static String password = null;
	private static HttpResponse response;
	private static RegistrationManager rManager = null;
	private static ArrayList<HashMap<String, String>> friendData = new ArrayList<HashMap<String,String>>();
	private static ArrayList<HashMap<String, String>> invitationData = new ArrayList<HashMap<String,String>>();
	public ArrayList<HashMap<String, String>> getInvitationData() {
		return invitationData;
	}

	public static void setInvitationData(ArrayList<HashMap<String, String>> invitationData) {
		RegistrationManager.invitationData = invitationData;
	}

	private static HashMap<String, String> selfData = new HashMap<String,String>();
	
	public ArrayList<HashMap<String, String>> getFriendData() {
		return friendData;
	}

	public void setFriendData(ArrayList<HashMap<String, String>> friendData) {
		RegistrationManager.friendData = friendData;
	}

	public void setSelfData(HashMap<String, String> selfData) {
		RegistrationManager.selfData = selfData;
	}

	public HashMap<String, String> getSelfData() {
		return selfData;
	}

	

	private RegistrationManager() {
		nm = NetworkManager.getEntity();
		nm.setHttpRequestListener(this);
	}

	public static RegistrationManager getEntity() {
		if (rManager == null) {
			rManager = new RegistrationManager();
		}
		return rManager;
	}

	public boolean putData(double latitude, double longitude, double altitude, double accuracy, Context ctx)
			throws Exception {
		if (ctx == null) {
			Log.e(LOG_TAG, "Ctx is null");
		}
		SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);

		id = settings.getString("id", "");
		email = settings.getString("email", "");
		password = settings.getString("password", "");

		String url = "http://awseb-e-q-awsebloa-czyxqbdjmzxo-1771358255.us-west-2.elb.amazonaws.com/webresources/users/"
				+ id + "/location";
		Header[] headers = { new BasicHeader("Content-type", "application/json"),
				new BasicHeader("Accept", "application/json") };
		Date dt = new Date(System.currentTimeMillis());
		Time t = new Time(System.currentTimeMillis());
		String dateString = dt.toString() + "T" + t.toString() + ".000+0000";

		Map<String, String> body = new HashMap<String, String>();
		body.put("latitude", String.valueOf(latitude));
		body.put("longitude", String.valueOf(longitude));
		body.put("altitude", String.valueOf(altitude));
		body.put("accuracy", String.valueOf(accuracy));
		body.put("id", id);
		body.put("time", dateString);
		nm.setHttpClientAuth(email, password);
		nm.makeRequest(url, body, headers, NetworkManager.PUT);
		try {
			synchronized (this) {
				this.wait();
			}
			;
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getMessage());
		}
		if (response != null) {
			Log.e(LOG_TAG, response.getStatusLine().toString());
			return true;
		}
		throw new Exception("Server unreachable. Please check you network connection.");
	}

	public JSONObject getData() throws Exception {
		SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);

		id = settings.getString("id", "");
		email = settings.getString("email", "");
		password = settings.getString("password", "");

		String url = "http://default-environment-5yrhjva6ce.elasticbeanstalk.com/webresources/users/" + id + "/friends";
		Header[] headers = { new BasicHeader("Content-type", "application/json"),
				new BasicHeader("Accept", "application/json") };
		nm.setHttpClientAuth(email, password);
		nm.makeRequest(url, null, headers, NetworkManager.GET);
		try {
			synchronized (this) {
				this.wait();
			}
			;
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getMessage());
		}
		if (response != null) {

			BufferedReader reader = new BufferedReader(
					new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
			StringBuilder builder = new StringBuilder();
			for (String line = null; (line = reader.readLine()) != null;) {
				builder.append(line).append("\n");
			}
			return new JSONObject(builder.toString());
		}
		throw new Exception("Server unreachable. Please check you network connection.");
	}

	public void setAppContext(Context ctx) {
		RegistrationManager.ctx = ctx;
	}

	public boolean registerId(final String displayName, final String email, final String avatar) throws Exception {
		String url = "http://awseb-e-q-awsebloa-czyxqbdjmzxo-1771358255.us-west-2.elb.amazonaws.com/webresources/users";
		Header[] headers = { new BasicHeader("Content-type", "application/json"), };
		Map<String, String> body = new HashMap<String, String>();
		body.put("displayName", displayName);
		body.put("email", email);
		body.put("avatar", avatar);
		nm.setHttpClientAuth(defUser, defPass);
		nm.makeRequest(url, body, headers, NetworkManager.POST);
		try {
			synchronized (this) {
				this.wait();
			}
			;
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getMessage());
		}
		if (response != null) {
			if (response.getStatusLine().toString().contains("Conflict")) {
				throw new Exception("User name is already registered.");
			}
			BufferedReader reader;
			try {
				reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
				StringBuilder builder = new StringBuilder();
				for (String line = null; (line = reader.readLine()) != null;) {
					builder.append(line).append("\n");
				}
				JSONTokener tokener = new JSONTokener(builder.toString());
				String[] splittedStr = tokener.toString().split("\"");
				for (String s : splittedStr) {
					if ("id".equals(s)) {
						SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
						SharedPreferences.Editor editor = settings.edit();
						editor.putString("id", splittedStr[3]);
						editor.putString("email", email);
						editor.commit();
						RegistrationManager.id = splittedStr[3];
						RegistrationManager.email = email;

						return true;
					}
				}
				throw new Exception(response.getStatusLine().toString());
			} catch (UnsupportedEncodingException e) {
				Log.e(LOG_TAG, e.getMessage());
			} catch (IllegalStateException e) {
				Log.e(LOG_TAG, e.getMessage());
			} catch (IOException e) {
				Log.e(LOG_TAG, e.getMessage());
			}

		}
		throw new Exception("Server unreachable. Please check you network connection.");
	}
	
	public boolean modifyUser(final String displayName, final String email, final String avatar) throws Exception {
		SharedPreferences settings = ctx.getSharedPreferences(RegistrationManager.PREFS_NAME, 0);
		String user = settings.getString("email", "");
		String pass = settings.getString("password", "");
		String url = "http://awseb-e-q-awsebloa-czyxqbdjmzxo-1771358255.us-west-2.elb.amazonaws.com/webresources/users/"+id;
		Header[] headers = { new BasicHeader("Content-type", "application/json"), };
		Map<String, String> body = new HashMap<String, String>();
		body.put("displayName", displayName);
		body.put("avatar", avatar);
		nm.setHttpClientAuth(user, pass);
		nm.makeRequest(url, body, headers, NetworkManager.PUT);
		try {
			synchronized (this) {
				this.wait();
			}
			;
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getMessage());
		}
		if (response != null) {
			return true;
		}
		throw new Exception("Server unreachable. Please check you network connection.");
	}

	public boolean registerUser(String pin, String password) throws Exception {
		String url = "http://awseb-e-q-awsebloa-czyxqbdjmzxo-1771358255.us-west-2.elb.amazonaws.com/webresources/users?pin="
				+ pin;
		Header[] headers = { new BasicHeader("Content-type", "application/json"), };
		nm.setHttpClientAuth(defUser, defPass);
		Map<String, String> body = new HashMap<String, String>();
		body.put("id", id);
		body.put("password", md5(email + ":API:" + password));
		nm.makeRequest(url, body, headers, NetworkManager.POST);
		try {
			synchronized (this) {
				this.wait();
			}
			;
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getLocalizedMessage());
		}

		if (response != null) {
			if (response.getStatusLine().toString().contains("Created")) {
				return true;
			} else if (response.getStatusLine().toString().contains("403")) {
				throw new Exception("PIN code is wrong, try again!");
			} else if (response.getStatusLine().toString().contains("429")) {
				throw new Exception("Too many failed attempt. User has been locked, try again later!");
			}
		}
		throw new Exception("Server unreachable. Please check you network connection.");

	}

	public boolean idRecovery(final String email) throws Exception {

		String url = "http://awseb-e-q-awsebloa-czyxqbdjmzxo-1771358255.us-west-2.elb.amazonaws.com/webresources/users?email="
				+ email;
		nm.setHttpClientAuth(defUser, defPass);
		nm.makeRequest(url, null, null, NetworkManager.GET);
		try {
			synchronized (this) {
				this.wait();
			}
			;
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getLocalizedMessage());
		}
		if (response != null) {
			if (response.getStatusLine().toString().contains("404")) {
				return false;
			} else if (response.getStatusLine().toString().contains("429")) {
				throw new Exception("Service locked out.");
			}
			BufferedReader reader;
			try {
				reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
				StringBuilder builder = new StringBuilder();
				for (String line = null; (line = reader.readLine()) != null;) {
					builder.append(line).append("\n");
				}
				JSONTokener tokener = new JSONTokener(builder.toString());
				String[] splittedStr = tokener.toString().split("\"");
				for (String s : splittedStr) {
					if ("id".equals(s)) {
						RegistrationManager.id = splittedStr[3];
						RegistrationManager.email = email;
						return true;
					}
				}
				throw new Exception(response.getStatusLine().toString());
			} catch (UnsupportedEncodingException e) {
				Log.e(LOG_TAG, e.getMessage());
			} catch (IllegalStateException e) {
				Log.e(LOG_TAG, e.getMessage());
			} catch (IOException e) {
				Log.e(LOG_TAG, e.getMessage());
			}

		}
		throw new Exception("Server unreachable. Please check you network connection.");

	}

	public void pwRecovery(final String pin, String password) {
		String url = "http://awseb-e-q-awsebloa-czyxqbdjmzxo-1771358255.us-west-2.elb.amazonaws.com/webresources/users/"
				+ id + "?pin=" + pin;
		nm.setHttpClientAuth(defUser, defPass);
		Header[] headers = { new BasicHeader("Content-type", "application/json"), };
		Map<String, String> body = new HashMap<String, String>();
		body.put("password", md5(email + ":API:" + password));

		nm.makeRequest(url, body, headers, NetworkManager.PUT);

		try {
			synchronized (this) {
				this.wait();
			}
			;
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getLocalizedMessage());
		}

	}

	public boolean login(String user, String pass) throws Exception {
		String url = "http://awseb-e-q-awsebloa-czyxqbdjmzxo-1771358255.us-west-2.elb.amazonaws.com/webresources/users";
		nm.setHttpClientAuth(user, pass);
		nm.makeRequest(url, null, null, NetworkManager.GET);
		Log.i(LOG_TAG, "Login started");
		try {
			synchronized (this) {
				this.wait();
			}
			;
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getLocalizedMessage());
		}

		if (response != null) {
			if (response.getStatusLine().toString().contains("404")) {
				Log.e(LOG_TAG, "Login response:404");
				throw new Exception("Login response:404");
			} else if (response.getStatusLine().toString().contains("401")) {
				Log.e(LOG_TAG, "Login response:401");
				throw new Exception("Login response:401");
			}
			BufferedReader reader;
			try {
				reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
				StringBuilder builder = new StringBuilder();
				for (String line = null; (line = reader.readLine()) != null;) {
					builder.append(line).append("\n");
				}
				JSONTokener tokener = new JSONTokener(builder.toString());
				String[] splittedStr = tokener.toString().split("\"");
				for (String s : splittedStr) {
					if ("id".equals(s)) {
						RegistrationManager.id = splittedStr[11];
						RegistrationManager.password = pass;
						RegistrationManager.email = user;
						SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
						SharedPreferences.Editor editor = settings.edit();
						editor.putString("id", splittedStr[11]);
						editor.putString("password", pass);
						editor.putString("email", user);
						editor.commit();
						Log.i(LOG_TAG, "Login succesful");
						return true;
					}
				}
				Log.e(LOG_TAG, "Login: " + response.getStatusLine().toString());
			} catch (UnsupportedEncodingException e) {
				Log.e(LOG_TAG, e.getMessage());
			} catch (IllegalStateException e) {
				Log.e(LOG_TAG, e.getMessage());
			} catch (IOException e) {
				Log.e(LOG_TAG, e.getMessage());
			}

		}
		Log.e(LOG_TAG, "Login response is null");
		throw new Exception("Server unreachable. Please check you network connection.");
	}

	public void read() {
		SharedPreferences settings = ctx.getSharedPreferences(RegistrationManager.PREFS_NAME, 0);
		String user = settings.getString("email", "");
		String pass = settings.getString("password", "");
		String id = settings.getString("id", "");
		String url = "http://awseb-e-q-awsebloa-czyxqbdjmzxo-1771358255.us-west-2.elb.amazonaws.com/webresources/users/"
				+ id;
		nm.setHttpClientAuth(user, pass);
		nm.makeRequest(url, null, null, NetworkManager.GET);

		try {
			synchronized (this) {
				this.wait();
			}
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getLocalizedMessage());
		}
	}

	public void sendInvitation(String email) throws Exception{
		SharedPreferences settings = ctx.getSharedPreferences(RegistrationManager.PREFS_NAME, 0);
		String user = settings.getString("email", "");
		String pass = settings.getString("password", "");
		
		String url = "http://default-environment-5yrhjva6ce.elasticbeanstalk.com/webresources/users/"+id+"/invitations";
		nm.setHttpClientAuth(user, pass);
		Header[] headers = { new BasicHeader("Content-type", "application/json"), };
		Map<String, String> body = new HashMap<String, String>();
		body.put("email", email.toLowerCase(Locale.getDefault()));
		nm.makeRequest(url, body, headers, NetworkManager.POST);
		
		try {
			synchronized (this) {
				this.wait();
			}
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getLocalizedMessage());
		}

		if (response != null) {
			if (response.getStatusLine().toString().contains("200")) {
				throw new Exception("Already invited");
			}
		}
		
	}
	
	public JSONArray getInvitations() throws Exception{
		SharedPreferences settings = ctx.getSharedPreferences(RegistrationManager.PREFS_NAME, 0);
		String user = settings.getString("email", "");
		String pass = settings.getString("password", "");
		String id = settings.getString("id", "");
		
		String url = "http://default-environment-5yrhjva6ce.elasticbeanstalk.com/webresources/users/" + id + "/invitations";
		nm.setHttpClientAuth(user, pass);
		nm.makeRequest(url, null, null, NetworkManager.GET);
		
		try {
			synchronized (this) {
				this.wait();
			}
			;
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getMessage());
		}
		if (response != null) {

			BufferedReader reader = new BufferedReader(
					new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
			StringBuilder builder = new StringBuilder();
			for (String line = null; (line = reader.readLine()) != null;) {
				builder.append(line).append("\n");
			}
			return new JSONArray(builder.toString());
		}
		throw new Exception("Server unreachable. Please check you network connection.");
		
	}
	
	public void acceptInvitation(String invId) throws Exception{
		SharedPreferences settings = ctx.getSharedPreferences(RegistrationManager.PREFS_NAME, 0);
		String user = settings.getString("email", "");
		String pass = settings.getString("password", "");
		
		String url = "http://default-environment-5yrhjva6ce.elasticbeanstalk.com/webresources/users/" + id + "/invitations/" + invId;
		nm.setHttpClientAuth(user, pass);
		nm.makeRequest(url, null, null, NetworkManager.PUT);
		try {
			synchronized (this) {
				this.wait();
			}
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getLocalizedMessage());
		}

		if (response != null) {
			if (!response.getStatusLine().toString().contains("200")) {
				throw new Exception("No such ID");
			}
		}
		
	}
	
	public void deleteInvitation(String invId) throws Exception{
		SharedPreferences settings = ctx.getSharedPreferences(RegistrationManager.PREFS_NAME, 0);
		String user = settings.getString("email", "");
		String pass = settings.getString("password", "");
		
		String url = "http://default-environment-5yrhjva6ce.elasticbeanstalk.com/webresources/users/"+id+"/invitations/" + invId;
		nm.setHttpClientAuth(user, pass);
		nm.makeRequest(url, null, null, NetworkManager.DELETE);
		try {
			synchronized (this) {
				this.wait();
			}
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getLocalizedMessage());
		}
	}
	
	public void delete() {
		SharedPreferences settings = ctx.getSharedPreferences(RegistrationManager.PREFS_NAME, 0);
		String user = settings.getString("email", "");
		String pass = settings.getString("password", "");
		
		String url = "http://awseb-e-q-awsebloa-czyxqbdjmzxo-1771358255.us-west-2.elb.amazonaws.com/webresources/users/"
				+ id;
		nm.setHttpClientAuth(user, pass);
		nm.makeRequest(url, null, null, NetworkManager.DELETE);

		try {
			synchronized (this) {
				this.wait();
			}
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getLocalizedMessage());
		}

	}

	public boolean deleteFriend(String friendId){
		SharedPreferences settings = ctx.getSharedPreferences(RegistrationManager.PREFS_NAME, 0);
		String user = settings.getString("email", "");
		String pass = settings.getString("password", "");
		String id = settings.getString("id", "");
		
		String url = "http://awseb-e-q-awsebloa-czyxqbdjmzxo-1771358255.us-west-2.elb.amazonaws.com/webresources/users/" + id + "/friends/" + friendId;
		nm.setHttpClientAuth(user, pass);
		nm.makeRequest(url, null, null, NetworkManager.DELETE);
		try {
			synchronized (this) {
				this.wait();
			}
		} catch (InterruptedException e1) {
			Log.e(LOG_TAG, e1.getLocalizedMessage());
		}

		if (response != null) {
			return true;
		}else{
			return false;
		}
	}
	
	public boolean downloadData() throws Exception{
		try {
			friendData = new ArrayList<HashMap<String,String>>();
			selfData = new HashMap<String,String>();
			JSONObject jData = RegistrationManager.getEntity().getData();
			for(String s : jData.getString("friends").split("\\{")){
				HashMap<String, String> subData = new HashMap<String, String>();
				for(String k : s.split(",")){
					String val = k.replace("\"", "");
					if(val.contains(MyListAdapter.KEY_NAME)){
						subData.put(MyListAdapter.KEY_NAME, val.split(":")[1]);
					}else if(val.contains(MyListAdapter.KEY_ID)){
						subData.put(MyListAdapter.KEY_ID, val.split(":")[1]);
					}else if(val.contains(MyListAdapter.KEY_DATE)){
						subData.put(MyListAdapter.KEY_DATE, val.split(":")[1]+":"+val.split(":")[2]);
					}else if(val.contains(MyListAdapter.KEY_LATITUDE)){
						if(val.split(":")[1].length()>=5){
							subData.put(MyListAdapter.KEY_LATITUDE, val.split(":")[1]);
						}else{
							subData.put(MyListAdapter.KEY_LATITUDE, val.split(":")[1]);
						}
					}else if(val.contains(MyListAdapter.KEY_LONGITUDE)){
						if(val.split(":")[1].length()>=5){
							subData.put(MyListAdapter.KEY_LONGITUDE, val.split(":")[1]);
						}else{
							subData.put(MyListAdapter.KEY_LONGITUDE, val.split(":")[1]);
						}
					}else if(val.contains(MyListAdapter.KEY_ACCURACY)){
						subData.put(MyListAdapter.KEY_ACCURACY, val.split(":")[1].replace("}", "").replace("]", ""));
					}
				}
				if(subData.size()>0){
					subData.put(MyListAdapter.KEY_SELF, "false");
					friendData.add(subData);
				}
			}
			for(String s : jData.getString("self").split("\\{")){
				for(String k : s.split(",")){
					String val = k.replace("\"", "");
					if(val.contains(MyListAdapter.KEY_NAME)){
						selfData.put(MyListAdapter.KEY_NAME, val.split(":")[1]);
					}else if(val.contains(MyListAdapter.KEY_ID)){
						selfData.put(MyListAdapter.KEY_ID, val.split(":")[1]);
					}else if(val.contains(MyListAdapter.KEY_DATE)){
						selfData.put(MyListAdapter.KEY_DATE, val.split(":")[1]+":"+val.split(":")[2]);
					}else if(val.contains(MyListAdapter.KEY_LATITUDE)){
						if(val.split(":")[1].length()>=5){
							selfData.put(MyListAdapter.KEY_LATITUDE, val.split(":")[1]);
						}else{
							selfData.put(MyListAdapter.KEY_LATITUDE, val.split(":")[1]);
						}
					}else if(val.contains(MyListAdapter.KEY_LONGITUDE)){
						if(val.split(":")[1].length()>=5){
							selfData.put(MyListAdapter.KEY_LONGITUDE, val.split(":")[1]);
						}else{
							selfData.put(MyListAdapter.KEY_LONGITUDE, val.split(":")[1]);
						}
					}else if(val.contains(MyListAdapter.KEY_ACCURACY)){
						selfData.put(MyListAdapter.KEY_ACCURACY, val.split(":")[1].replace("}", "").replace("]", ""));
					}
				}
			}
			return true;
		} catch (Exception e) {
			throw e;
		}
	}
	
	public boolean downloadInvitations() throws Exception{
		try {
			invitationData = new ArrayList<HashMap<String,String>>();
			JSONArray jArray = RegistrationManager.getEntity().getInvitations();
			for(int i=0; i<jArray.length(); i++)
			{
			     JSONObject obj=jArray.getJSONObject(i);
			     try{
			    	 HashMap<String, String> subData = new HashMap<String, String>();
				     subData.put(InvitationsListAdapter.KEY_DISPLAYNAME,obj.getString(InvitationsListAdapter.KEY_DISPLAYNAME));
				     subData.put(InvitationsListAdapter.KEY_EMAIL,obj.getString(InvitationsListAdapter.KEY_EMAIL));
				     subData.put(InvitationsListAdapter.KEY_GUID,obj.getString(InvitationsListAdapter.KEY_GUID));
				     subData.put(InvitationsListAdapter.KEY_OUTGOING,obj.getString(InvitationsListAdapter.KEY_OUTGOING));
				     subData.put(InvitationsListAdapter.KEY_UNSEEN,obj.getString(InvitationsListAdapter.KEY_UNSEEN));
				     invitationData.add(subData);
			     }catch(Exception e){
			     }
			}	
			return true;
		} catch (Exception e) {
			throw e;
		}
	}
	
	public static final String md5(final String s) {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
			digest.update(s.getBytes());
			byte messageDigest[] = digest.digest();

			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++) {
				String h = Integer.toHexString(0xFF & messageDigest[i]);
				while (h.length() < 2)
					h = "0" + h;
				hexString.append(h);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	@Override
	public void onHttpResult(HttpResponse response) {
		RegistrationManager.response = response;
		Log.i(LOG_TAG, "Response received");
		synchronized (this) {
			try {
				this.notifyAll();
			} catch (Exception e) {
				Log.e(LOG_TAG, e.getLocalizedMessage());
			}
		}
		;
	}

}
